package com.ailiwu.www.ailiwu.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ailiwu.www.ailiwu.Fragment.CommentFragment;
import com.ailiwu.www.ailiwu.Fragment.IntroduceFragment;
import com.ailiwu.www.ailiwu.R;
import com.ailiwu.www.ailiwu.base.BaseActivity;
import com.ailiwu.www.ailiwu.base.MyApplication;
import com.ailiwu.www.ailiwu.bean.CommodityDetail;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class CommodityActivity extends BaseActivity {
    private ViewPager vp_commodity;//商品图片展示ViewPager
    private TextView tv_name, tv_price, tv_description;
    private ArrayList<ImageView> ivList;//商品图片展示的图片集
    private List<View> pointList;//圆点集合
    private LinearLayout llPoints;//圆点放置位置的 LinearLayout
    private String url_commodity;//商品详情页面url
    private ArrayList<String> imageUrlList;
    private MyPagerAdapter myPagerAdapter;//商品图片展示
    private int currentPos = 0;//商品图片展示初始展示页
    private TabLayout tbLayout;//标签
    private ViewPager vp_commont;//图文介绍页面和评论页面所放的ViewPager
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private List<Fragment> fragments = new ArrayList<>();//页卡视图集合
    private MyFragmentAdapter mFragmentAdapter;
    private int commodityId;//商品ID
    private String detail_html;//图文介绍页面使用的Html字符串
    private Button btn_goTianMao;//去天猫按钮
    private String purchase_url;//开启天猫页面的URL

    @Override
    protected void loadXml() {
        setContentView(R.layout.activity_commodity);
    }

    @Override
    protected void getIntentData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        this.url_commodity = intent.getStringExtra("url_commodity");
        this.commodityId = intent.getIntExtra("COMMODITYID", -1);
    }
    //右上角菜单位置分享按钮初始化
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.share, menu);
        return true;
    }
    //分享按钮点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_share:
                ShareSDK.initSDK(this);
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();

                // title标题：微信、QQ（新浪微博不需要标题）
                oks.setTitle("我是分享标题");  //最多30个字符

                // text是分享文本：所有平台都需要这个字段
                oks.setText("我是分享文本，啦啦啦~http://uestcbmi.com/");  //最多40个字符

                // imagePath是图片的本地路径：除Linked-In以外的平台都支持此参数
                //oks.setImagePath(Environment.getExternalStorageDirectory() + "/meinv.jpg");//确保SDcard下面存在此张图片

                //网络图片的url：所有平台
                oks.setImageUrl("http://7sby7r.com1.z0.glb.clouddn.com/CYSJ_02.jpg");//网络图片rul

                // url：仅在微信（包括好友和朋友圈）中使用
                oks.setUrl("http://sharesdk.cn");   //网友点进链接后，可以看到分享的详情

                // Url：仅在QQ空间使用
                oks.setTitleUrl("http://www.baidu.com");  //网友点进链接后，可以看到分享的详情

                // 启动分享GUI
                oks.show(this);

                return true;
            case android.R.id.home://navigation菜单
                finish();
                return true;
            default:

                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(this);
    }
    @Override
    protected void initView() {
        btn_goTianMao = (Button) findViewById(R.id.btn_goTianMao);
        vp_commodity = (ViewPager) findViewById(R.id.vp_commodity);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_description = (TextView) findViewById(R.id.tv_description);
        llPoints = (LinearLayout) findViewById(R.id.ll_point);

        setTabViewPager();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

    }

    private void setTabViewPager() {
        vp_commont = (ViewPager) findViewById(R.id.vp_comment);
        tbLayout = (TabLayout) findViewById(R.id.tbLayout);

        //创建自定义FragmentPagerAdapter
        mFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager());
        vp_commont.setAdapter(mFragmentAdapter);
    }

    /**
     * 初始化数据商品详情页面数据
     */
    @Override
    protected void initData() {
        ivList = new ArrayList<ImageView>();
        HttpUtils get = new HttpUtils();
        //设置连接超时时间
        get.configTimeout(100000);
        //设置缓存区中数据的存储时间，单位为毫秒,这里设置为1天.
        get.configDefaultHttpCacheExpiry(24 * 3600 * 1000);
        //设置缓存区的大小，单位是b字节
        get.configHttpCacheSize(4 * 1024 * 1024);

        get.send(HttpRequest.HttpMethod.GET, url_commodity, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String Json = responseInfo.result;

                //解析商品详情页数据
                Gson gson = new Gson();
                CommodityDetail commodityDetail = gson.fromJson(Json, CommodityDetail.class);
                imageUrlList = commodityDetail.data.image_urls;
                detail_html = commodityDetail.data.detail_html;
                purchase_url = commodityDetail.data.purchase_url;

                // 展示商品图片信息
                initImageList();

                myPagerAdapter = new MyPagerAdapter();
                vp_commodity.setAdapter(myPagerAdapter);

                // 展示商品文字信息
                tv_name.setText(commodityDetail.data.name);
                tv_price.setText(commodityDetail.data.price);
                tv_description.setText(commodityDetail.data.description);

                //添加页卡Fragment
                fragments.add(new IntroduceFragment().newInstance(detail_html));
                fragments.add(new CommentFragment().newInstance(commodityId));

                //添加图文介绍和评论页卡标题
                mTitleList.add("图文介绍");
                mTitleList.add("评论(" + commodityDetail.data.comments_count + ")");

                //添加tab选项卡
                tbLayout.addTab(tbLayout.newTab().setText(mTitleList.get(0)));
                tbLayout.addTab(tbLayout.newTab().setText(mTitleList.get(1)));
                //将TabLayout和ViewPager关联起来。
                tbLayout.setupWithViewPager(vp_commont);
                mFragmentAdapter.notifyDataSetChanged();
                //TODO 设置喜欢的CheckBox的值
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.i("oye", "failure:  " + e.getMessage() + "  " + s);
            }
        });
    }


    /**
     * 初始化商品图片集合
     * 在图片集合加载完成后再初始化圆点
     */
    private void initImageList() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .bitmapConfig(Bitmap.Config.RGB_565)                //设置图片的解码类型
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)   //设置图片以如何的编码方式显示
                .cacheInMemory(true)                                // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                                  // 设置下载的图片是否缓存在SD卡中
                .build();

        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(MyApplication.mContext));

        for (int i = 0; i < imageUrlList.size(); i++) {
            ImageView tempImageView = new ImageView(CommodityActivity.this);
            tempImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                    RadioGroup.LayoutParams.MATCH_PARENT,
                    RadioGroup.LayoutParams.MATCH_PARENT);
            tempImageView.setLayoutParams(layoutParams);
            // 开始加载图片
            imageLoader.displayImage(imageUrlList.get(i), tempImageView, options);
            ivList.add(tempImageView);
            if (ivList.size() == imageUrlList.size()) {
                initPoints();
                // 设置滑动监听
                vp_commodity.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        // Log.i("oye", "切换到:"+position);
                        pointList.get(currentPos).setEnabled(true);
                        pointList.get(position).setEnabled(false);
                        currentPos = position;
                    }

                    @Override
                    public void onPageSelected(int position) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });
            }
        }
    }

    /**
     * 初始化圆点
     */
    private void initPoints() {

        pointList = new ArrayList<View>();
        for (int i = 0; i < ivList.size(); i++) {
            View point = new View(this);
            point.setBackgroundResource(R.drawable.selector_commodity_point);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
            params.setMargins(5, 0, 5, 0);
            point.setLayoutParams(params);
            pointList.add(point);
            if (i == 0) {
                // 默认一开始显示的是第一页
                point.setEnabled(false);
            } else {
                point.setEnabled(true);
            }
            // 让每个圆点都记录下自己的下标
            point.setTag(i);
            // 将圆点添加到布局中
            llPoints.addView(point);
        }
    }

    @Override
    protected void setListener() {
        btn_goTianMao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CommodityActivity.this,PurchaseActivity.class);
                intent.putExtra("PURCHASE_URL", purchase_url);
                startActivity(intent);
            }
        });
    }


    /**
     * 商品详情图片展示ViewPager适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return ivList == null ? 0 : ivList.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(ivList.get(position));
            return ivList.get(position);
        }


        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(ivList.get(position));
        }
    }


    /**
     * 图文介绍和评论 ViewPager适配器
     */
    private class MyFragmentAdapter extends FragmentPagerAdapter {
        public MyFragmentAdapter(FragmentManager fm) {

            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            return fragments.get(position);
        }

        @Override
        public int getCount() {

            return fragments == null ? 0 : fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);
        }
    }


}
